using Microsoft.Extensions.Configuration;

namespace FastNetCore.Framework.Configurations;

public class ConfigurationUtils
{
    private static IConfiguration _mConfiguration;
    

    public static IConfiguration GetConfiguration()
    {
        return _mConfiguration;
    }
    
    
    public static void Initializer(IConfiguration configuration)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }
        _mConfiguration = configuration;
    }

    /// <summary>
    /// 获取指定键的配置值
    /// </summary>
    /// <param name="key">配置键</param>
    /// <returns></returns>
    public static string GetValue(string key)
    {
        CheckInitialized();
        return _mConfiguration.GetValue<string>(key);
    }

    /// <summary>
    /// 获取指定键的配置值，带默认值
    /// </summary>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static string GetValue(string key, string defaultValue)
    {
        return GetValue(key)??defaultValue;
    }

    /// <summary>
    /// 获取指定键的配置值
    /// </summary>
    /// <param name="key"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T GetValue<T>(string key) where T : class,new()
    {
        CheckInitialized();
        T value = new T();
        _mConfiguration.GetSection(key).Bind(value);
        
        return value;
    }

    /// <summary>
    /// 检查配置获取工具是否初始化。
    /// </summary>
    /// <exception cref="ArgumentNullException"></exception>
    private static void CheckInitialized()
    {
        if (_mConfiguration == null)
            throw new ArgumentNullException("ConfigurationUtils未初始化");
    }
    

}